package com.pocketmenu.ui;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.pocketmenu.business.Constants;
import com.pocketmenu.persistence.UserProfileDataSource;

public class LoginActivity extends Activity {
	
private String elEmail="";
private String laPW="";
private int respuesta=2;
private String profile[]={};

private static String APP_ID = "450511611661417";
public static Facebook facebook;
public static AsyncFacebookRunner mAsyncRunner;
private boolean waitingForThread = true;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public static boolean logeadoFB=false;
//private Context context=this;
UserProfileDataSource palFace = new UserProfileDataSource(this);
protected String name;
protected String email;
protected String gender;
protected String id;


    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        
//        if (savedInstanceState == null) {
//            // Add the fragment on initial activity setup
//            mainFragment = new FBfragment();
//            
//            getSupportFragmentManager()
//            .beginTransaction()
//            .add(android.R.id.content, mainFragment)
//            .commit();
//        } else {
//            // Or set the fragment from restored state info
//            mainFragment = (FBfragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
//        }
        
        setContentView(R.layout.activity_login);
        facebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(facebook);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }
    
    
    public void FBLog_Click(View v){
    	loginToFacebook();
    }
    
    @SuppressWarnings("deprecation")
	public void loginToFacebook() {
        mPrefs = getPreferences(MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);
     
        if (access_token != null) {
            facebook.setAccessToken(access_token);
        }
     
        if (expires != 0) {
            facebook.setAccessExpires(expires);
        }
        
        Log.i("Error", "Facebook");
        if (!logeadoFB) {
        	Log.i("Error", "Facebook");
            facebook.authorize(this,
                    new String[] { "email", "publish_stream", "read_stream" },
                    new DialogListener() {
     
                        public void onCancel() {
                            // Function to handle cancel event
                        	Log.i("Error", "Facebook");
                        }
     
                        public void onComplete(Bundle values) {
                        	Log.i("Error", "Facebook");
                            // Function to handle complete event
                            // Edit Preferences and update facebook acess_token
                            SharedPreferences.Editor editor = mPrefs.edit();
                            editor.putString("access_token",
                                    facebook.getAccessToken());
                            editor.putLong("access_expires",
                                    facebook.getAccessExpires());
                            editor.commit();
                            getProfileInformation();
                            logeadoFB=true;
                            
                        }
     
                        public void onError(DialogError error) {
                            // Function to handle error
                        	Log.i("Error", "Facebook");
                        }
     
                        public void onFacebookError(FacebookError fberror) {
                            // Function to handle Facebook errors
                        	Log.i("Error", "Facebook");
                        }
     
                    });
            
//            while(waitingForThread)
//            {}
//            this.getProfileInformation();
            
            
            
//            this.finish();
        }
        else{
        	this.logoutFromFacebook();
        	
        	
//        	this.finish();
        }
    }
    
    @SuppressWarnings("deprecation")
	public void getProfileInformation() {
    	
    	
    	mAsyncRunner.request("me", new RequestListener() {
            @Override
			public void onComplete(String response, Object state) {
//                Log.d("Profile", response);
                String json = response;
                
                try {
                    JSONObject profile = new JSONObject(json);
                    // getting name of the user
                    name = profile.getString("name");
                    // getting email of the user
                    email = profile.getString("email");
                    id = profile.getString("id");
                    gender = profile.getString("gender");
                    if(gender.equals("male")){
                    	gender="M";
                    }
                    else{
                    	gender="F";
                    }
                    
//                    Log.i("system.out.facebook", name+";"+email+";"+id+";"+gender);
                    
                    
         	    	
         	    	palFace.open(); 
         		  palFace.create(name, email, id, "", "", gender);
         	    	
         	    	palFace.close();
         	    	
         	    	Thread networkThread = new Thread() {
         	       	    @Override
         	       	    public void run() {
         	       	      
         	   	    	//request       	    
         	       	    String metodo = "agregarUsuario";	
         	           SoapObject request= new SoapObject(Constants.namespace, metodo);
         	           request.addProperty("UserProfileAddress", "");
         	           request.addProperty("Age", "");
         	           request.addProperty("Email", email);
         	           request.addProperty("UserProfilePassword", id);
         	           request.addProperty("Sex", gender);
         	           request.addProperty("Name", name);

         	           //modelo sobre
         	           SoapSerializationEnvelope sobre= new SoapSerializationEnvelope(SoapEnvelope.VER11);

         	           sobre.dotNet = true;

         	           sobre.setOutputSoapObject(request);

         	           //transporte
         	           HttpTransportSE transporte= new HttpTransportSE(Constants.url,2000);
         	           
         	           transporte.debug = true;           

         	           //llamada

         	           try {
         	    			transporte.call(Constants.namespace+metodo, sobre);
         	    			
         	    			//resultado
         	    			SoapPrimitive resultado= (SoapPrimitive) sobre.getResponse();
         	    			String nombre=resultado.toString();
         	    			
         	    			
         	    			Log.i("system.out", nombre);
         	    		} catch (IOException e) {
         	    			// TODO Auto-generated catch block
         	    			e.printStackTrace();
         	    		}
         	           catch (XmlPullParserException e) {
         	    			// TODO Auto-generated catch block
         	        	   Log.i("system.ou2t",transporte.responseDump);
         	    		}
         	                   
         	       	      }
         	       	      
         	       	    };
         	       	    networkThread.start();
         	       	 
         	    
         	    	finishActivity();
                    runOnUiThread(new Runnable() {
     
                        @Override
						public void run() {
                           
                        }
     
                    });
     
                } catch (JSONException e) {
                	Log.i("Error", "Json");
                }
            }
     
            @Override
			public void onIOException(IOException e, Object state) {
            	Log.i("Error", "IO");
            }
     
            @Override
			public void onFileNotFoundException(FileNotFoundException e,
                    Object state) {
            	Log.i("Error", "File");
            }
     
            @Override
			public void onMalformedURLException(MalformedURLException e,
                    Object state) {
            	Log.i("Error", "URL");
            }
     
            @Override
			public void onFacebookError(FacebookError e, Object state) {
            	Log.i("Error", "Facebook");
            }
        });
        
        
    }
    
    public void bNuevaCuenta_Click(View v)
    {
    	Intent intent = new Intent(this, NewUserActivity.class);		      			
	    startActivity(intent);
    }
    public void bIngresar_click(View v)
    {
    	
    	EditText email=(EditText) findViewById(R.id.etEmailSignIn);
    	EditText pw=(EditText) findViewById(R.id.etPasswordSignIn);
    	elEmail=email.getText().toString();
    	laPW=pw.getText().toString();
    	Thread networkThread = new Thread() {
       	    @Override
       	    public void run() {
       	    	
    	//request       	    
   	    String metodo = "darUsuario";	
       SoapObject request= new SoapObject(Constants.namespace, metodo);
       request.addProperty("Email",elEmail);
       request.addProperty("UserProfilePassword",laPW);

       //modelo sobre
       SoapSerializationEnvelope sobre= new SoapSerializationEnvelope(SoapEnvelope.VER11);

       sobre.dotNet = true;

       sobre.setOutputSoapObject(request);

       //transporte
       HttpTransportSE transporte= new HttpTransportSE(Constants.url,2000);
       
       transporte.debug = true;           

       //llamada

       try {
			transporte.call(Constants.namespace+metodo, sobre);
			
			//resultado
			SoapPrimitive resultado= (SoapPrimitive) sobre.getResponse();
			String nombre=resultado.toString();
			Log.i("system.out", nombre);
			if(!nombre.equals("0")){
				respuesta=1;
				profile=nombre.split("\\*");
			}
			else{
				respuesta=0;
			}
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
    	   Log.i("system.ou2t",transporte.responseDump);
		}
       
     	      }
     	      
     	    };
     	   networkThread.start();
     	   while(respuesta==2){
     		   
     	   }
     	   if(respuesta!=0){
     		   
     		  UserProfileDataSource datasourceProfile = new UserProfileDataSource(this);
     	    	
     	    	datasourceProfile.open(); 
     		  datasourceProfile.create(profile[6]
     	    			, profile[3]
     	    			, profile[4]
     	    			, profile[2]
     	    			, profile[1]
     	    			, profile[5]);
     	    	
     	    	datasourceProfile.close();
     	    	finish();
     	    	
     	   }
     	   else{
     		  Toast.makeText(getApplicationContext(), "Error: email y/o password no coinciden" , Toast.LENGTH_SHORT).show();
     		  respuesta=2;
     	   }
    	
    	
    	
    }
    
    @SuppressWarnings("deprecation")
	public void logoutFromFacebook() {
    	
    	
    	
        
        mAsyncRunner.logout(this, new RequestListener() {
            public void onComplete(String response, Object state) {
                Log.d("Logout from Facebook", response);
                if (Boolean.parseBoolean(response) == true) {
                    // User successfully Logged out
                	logeadoFB=false;
                }
            }
     
            public void onIOException(IOException e, Object state) {
            }
     
            public void onFileNotFoundException(FileNotFoundException e,
                    Object state) {
            }
     
            public void onMalformedURLException(MalformedURLException e,
                    Object state) {
            }
     
            public void onFacebookError(FacebookError e, Object state) {
            }
        });
    }
    
    private void finishActivity()
    {
    	finish();
    }
}
